import store from '@/store'
import axios from 'axios'
// import sign from './sign-request'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 30000
})

let toast
let loading

function blobToDataURL(blob) {
  return new Promise(resolve => {
    let a = new FileReader()
    a.onload = function (e) {
      resolve(e.target.result)
    }
    a.readAsDataURL(blob)
  })
}

const isArray = data => Object.prototype.toString.call(data) === '[object Array]'

const showToast = (toast, data, message) => {
  if (toast) {
    const { code, msg } = data
    const isToastArray = isArray(toast)
    let needToast = (isToastArray && toast.indexOf(code) === -1) || (!isToastArray && toast)
    if (needToast) {
      if (code === 0) {
        Message.success(msg || message)
      } else {
        Message.error(msg || message)
      }
    }
  }
}

service.interceptors.request.use((request) => {
  request.toast = toast
  request.loading = loading
  const { token } = store.state.app.userInfo
  request.headers['access-token'] = token
  // APP签名验证
  // sign.use(request)
  return request
})

service.interceptors.response.use(
  async (response) => {
    const { data, config, headers } = response
    if (headers && headers['content-type'] === 'image/jpeg') {
      const base64Str = await blobToDataURL(new Blob([response.data], { type: headers['content-type'] }))
      response.data = base64Str
      return response
    } else if (headers['content-type'] === 'application/octet-stream') {
      const blob = new Blob([data], { type: headers['content-type'] })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      const disposition = headers['content-disposition']
      const filename = decodeURIComponent(escape(disposition.substring(disposition.indexOf('filename=') + 9, disposition.length)))
      downloadElement.href = href
      downloadElement.download = decodeURI(filename) // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放blob对象
      return response
    }
    const { loading = config.method !== 'get', toast = loading } = config
    if (data.code === 12 || data.code === 10 || data.code === 21) {
      store.commit('app/setUserInfo', {})
      location.href = '/login'
    }
    if (data.code === 0) {
      showToast(toast, data, '操作成功')
      return data
    } else {
      showToast(true, data, '请求错误')
      return Promise.reject(new Error(data.msg))
    }
  },
  (err) => {
    const data = { code: 1000, msg: '网络异常', data: {} }
    err.data = data
    showToast(true, data, '网络异常')
    return Promise.reject(err)
  }
)

const fetch = options => {
  toast = options.toast
  loading = options.loading
  return service.request(options)
}

export default fetch
